<?php

class Application_Model_Tasks extends Zend_Db_Table_Abstract
{
    protected $_name = 'tasks';
    protected $_primary = 'id';

    public function createTask($params)
    {
        $data = array(
            'name' => $params['name'],
            'info' => $params['info'],
            'date_start' => $params['date_start'],
            'date_end' => $params['date_end'],
            'supervisor' => $params['supervisor'],
            'hours_expected' => $params['hours_expected'],
            'status' => $params['status']
        );

        $this->insert($data);
    }

    public function editTask($id, $params)
    {
        $data = array(
            'name' => $params['name'],
            'info' => $params['info'],
            'date_start' => $params['date_start'],
            'date_end' => $params['date_end'],
            'supervisor' => $params['supervisor'],
            'hours_expected' => $params['hours_expected'],
            'status' => $params['status']
        );
        $where = $this->getAdapter()->quoteInto('id = ?', intval($id));

        $this->update($data, $where);
    }

    public function getTask($id)
    {
        $where = $this->getAdapter()->quoteInto('id = ?', intval($id));
        $row = $this->fetchRow($where);

        if ($row) {
            return $row->toArray();
        } else {
            throw new Exception('Tasks not found');
        }
    }

    public function getTaskUsers($id)
    {
        $st = $this->getAdapter()->query('
            SELECT u.id, u.first_name, u.last_name, SUM(t.hours) AS hours
            FROM tickets t
            JOIN users u ON u.id = t.user_id
            JOIN tasks a ON a.id = t.task_id
            WHERE t.task_id = ?
            GROUP BY u.id
            ORDER BY u.first_name ASC
        ', intval($id));

        return $st->fetchAll();
    }

    public function getTaskList()
    {
        return $this->fetchAll()->toArray();
    }

    public function getTaskListSimple()
    {
        $data = $this->getTaskList();
        $out = array();

        foreach ($data as $row) {
            $out[$row['id']] = $row['name'];
        }

        return $out;
    }
}
